import React, { useState, useRef, useEffect } from 'react';
import axios from 'axios';
import './Dashboard.css';

function Dashboard({ token, onUnauthorized }) {
  const [selectedFile, setSelectedFile] = useState(null);
  const [fileName, setFileName] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [hasCredentials, setHasCredentials] = useState(false);
  const [loading, setLoading] = useState(true);
  const authCheckDone = useRef(false);

  useEffect(() => {
    if (authCheckDone.current) return;
    authCheckDone.current = true;

    const checkCredentials = async () => {
      try {
        const response = await axios.get('http://sg.neuq.org:7788/check-credential-status', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });
        setHasCredentials(response.data.hasCredentials);
        if (response.data.hasCredentials) {
          setSuccess('Credential created successfully');
        }
      } catch (error) {
        if (error.response?.status === 401) {
          onUnauthorized();
        } else {
          setError('Failed to check credential status');
        }
      } finally {
        setLoading(false);
      }
    };

    checkCredentials();
  }, [token, onUnauthorized]);

  const handleFileChange = (event) => {
    const file = event.target.files[0];
    setSelectedFile(file);
    setFileName(file ? file.name : '');
    setError('');
    setSuccess('');
  };

  const handleSubmit = async () => {
    if (!selectedFile) {
      setError('Please select a CSR file first');
      return;
    }

    const formData = new FormData();
    formData.append('csr', selectedFile);

    try {
      await axios.post('http://sg.neuq.org:7788/test-credential', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${token}`
        }
      });

      setSuccess('Credential created successfully');
      setHasCredentials(true);
      setSelectedFile(null);
      setFileName('');
    } catch (err) {
      if (err.response?.status === 401) {
        onUnauthorized();
      } else {
        setError(err.response?.data?.msg || 'An unexpected error occurred');
      }
    }
  };

  const handleDownload = async (type) => {
    try {
      const endpoint = type === 'key' ? '/download-key' : '/download-certificate';
      const response = await axios.get(`http://sg.neuq.org:7788${endpoint}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        },
        responseType: 'blob'
      });

      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `${type}.pem`);
      document.body.appendChild(link);
      link.click();
      link.remove();
    } catch (err) {
      if (err.response?.status === 401) {
        onUnauthorized();
      } else {
        setError(`Failed to download ${type}`);
      }
    }
  };

  if (loading) {
    return <div className="dashboard-container">Loading...</div>;
  }

  return (
    <div className="dashboard-container">
      {error && <div className="error-message">{error}</div>}
      {success && <div className="success-message">{success}</div>}

      {!hasCredentials ? (
        <div className="upload-section">
          <input
            type="file"
            onChange={handleFileChange}
            style={{ display: 'none' }}
            id="csr-upload"
            accept=".csr,.pem"
          />
          <div className="button-container">
            <label htmlFor="csr-upload" className="dashboard-button primary-button">
              Select CSR File
            </label>
            <button
              className="dashboard-button secondary-button"
              onClick={handleSubmit}
              disabled={!selectedFile}
            >
              Upload CSR
            </button>
          </div>
          {fileName && <div className="file-name">{fileName}</div>}
        </div>
      ) : (
        <div className="credential-section">
          <div className="button-container">
            <button
              className="dashboard-button primary-button"
              onClick={() => handleDownload('key')}
            >
              Download Private Key
            </button>
            <button
              className="dashboard-button primary-button"
              onClick={() => handleDownload('certificate')}
            >
              Download Certificate
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

export default Dashboard;